﻿using CommonLibrary.Helper;

using CuteWallpaperDemo.Managers;
using CuteWallpaperDemo.ViewModels;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace CuteWallpaperDemo.Views
{
    /// <summary>
    /// ViewPictureWindow.xaml 的交互逻辑
    /// </summary>
    public partial class ViewPictureWindow
    {
        public ViewPictureWindow()
        {
            InitializeComponent();

            this.Left = 0.0;
            this.Top = 0.0;
            this.Width = System.Windows.SystemParameters.PrimaryScreenWidth;
            this.Height = System.Windows.SystemParameters.PrimaryScreenHeight;

            //this.SourceInitialized += Window1_SourceInitialized;
            this.Loaded += ViewPictureWindow_Loaded;
        }

        private void ViewPictureWindow_Loaded(object sender, RoutedEventArgs e)
        {
            if (this.Parameter is string url)
            {
                string cache = DomainHelper.GetCachedFilePath(url);
                Part_Image.Source = new BitmapImage(new Uri(cache));

                this.Title = System.IO.Path.GetFileName(url);
            }
        }

        private bool mouseDown;
        Point moveStart;

        private void ImgMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (scaler.ScaleX <= 1) return;
            Part_ImageContainer.CaptureMouse();
            mouseDown = true;
            moveStart = e.GetPosition(Part_ImageContainer);
        }

        private void ImgMouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {

        }

        private void ImgMouseUp(object sender, MouseButtonEventArgs e)
        {
            mouseDown = false;
            Part_ImageContainer.ReleaseMouseCapture();
        }

        private void ImgMouseMove(object sender, MouseEventArgs e)
        {
            var mouseEnd = e.GetPosition(Part_ImageContainer);           // 鼠标移动时，获取鼠标相对Part_ImageContainer的点
            if (mouseDown)
            {
                if (e.LeftButton == MouseButtonState.Pressed)           // 按下鼠标左键，移动图片
                {
                    DoMove(mouseEnd);
                }
            }
        }

        private void ImgMouseWheel(object sender, MouseWheelEventArgs e)
        {
            if (scaler.ScaleX <= 1)
            {
                Part_Image.RenderTransformOrigin = new Point(0.5, 0.5);
            }
            else
            {
                Part_Image.RenderTransformOrigin = new Point(0, 0);
            }

            var point = e.GetPosition(Part_Image);
            var delta = e.Delta > 0 ? 0.1 : -0.1;
            DoScale(point, delta);
        }


        /// <summary>
        /// 移动图片
        /// </summary>
        /// <param name="moveEndPoint">移动图片的终点（相对于Part_ImageContainer）</param>
        private void DoMove(Point moveEndPoint)
        {
            // 考虑到旋转的影响，因此将两个点转换到Part_Image坐标系，计算x、y的增量
            Point start = Part_ImageContainer.TranslatePoint(moveStart, Part_Image);
            Point end = Part_ImageContainer.TranslatePoint(moveEndPoint, Part_Image);


            // 判断一下，如果scale很大的时候，移动会很迟缓。此时应该将移动放大
            if (scaler.ScaleX > 7)
            {
                transer.X += (end.X - start.X) * 4;
                transer.Y += (end.Y - start.Y) * 4;
            }
            else if (scaler.ScaleX > 5)
            {
                transer.X += (end.X - start.X) * 3;
                transer.Y += (end.Y - start.Y) * 3;
            }
            else if (scaler.ScaleX > 3)
            {
                transer.X += (end.X - start.X) * 2;
                transer.Y += (end.Y - start.Y) * 2;
            }
            else if (scaler.ScaleX < 0.5)
            {
                transer.X += (end.X - start.X) * 0.5;
                transer.Y += (end.Y - start.Y) * 0.5;
            }
            else
            {
                transer.X += (end.X - start.X);
                transer.Y += (end.Y - start.Y);
            }
            moveStart = moveEndPoint;



            // W+w > 2*move_x > -((2*scale-1)*w + W)  水平平移限制条件
            // H+h > 2*move_y > -((2*scale-1)*h + H)  垂直平移限制条件

            if (transer.X * 2 > Part_Image.ActualWidth + Part_ImageContainer.ActualWidth - 20)
                transer.X = (Part_Image.ActualWidth + Part_ImageContainer.ActualWidth - 20) / 2;

            if (-transer.X * 2 > (2 * scaler.ScaleX - 1) * Part_Image.ActualWidth + Part_ImageContainer.ActualWidth - 20)
                transer.X = -((scaler.ScaleX - 0.5) * Part_Image.ActualWidth + Part_ImageContainer.ActualWidth / 2 - 10);

            if (transer.Y * 2 > Part_Image.ActualHeight + Part_ImageContainer.ActualHeight - 20)
                transer.Y = (Part_Image.ActualHeight + Part_ImageContainer.ActualHeight - 20) / 2;

            if (-transer.Y * 2 > (2 * scaler.ScaleY - 1) * Part_Image.ActualHeight + Part_ImageContainer.ActualHeight - 20)
                transer.Y = -((scaler.ScaleY - 0.5) * Part_Image.ActualHeight + Part_ImageContainer.ActualHeight / 2 - 10);
        }

        /// <summary>
        /// 缩放图片。最小为0.1倍，最大为30倍
        /// </summary>
        /// <param name="point">相对于图片的点，以此点为中心缩放</param>
        /// <param name="delta">缩放的倍数增量</param>
        private void DoScale(Point point, double delta)
        {
            // 限制最大、最小缩放倍数
            if (scaler.ScaleX + delta < 0.1 || scaler.ScaleX + delta > 30) return;

            scaler.ScaleX += delta;
            scaler.ScaleY += delta;

            if (scaler.ScaleX > 1)
            {
                transer.X -= point.X * delta;
                transer.Y -= point.Y * delta;
            }
            else
            {
                transer.X = 0;
                transer.Y = 0;
            }

        }

        private void Window1_SourceInitialized(object sender, EventArgs e)
        {
            WindowInteropHelper helper = new WindowInteropHelper(this);
            HwndSource source = HwndSource.FromHwnd(helper.Handle);
            source.AddHook(WndProc);
        }

        const int WM_SYSCOMMAND = 0x0112;
        const int SC_MOVE = 0xF010;

        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {

            switch (msg)
            {
                case WM_SYSCOMMAND:
                    int command = wParam.ToInt32() & 0xfff0;
                    if (command == SC_MOVE)
                    {
                        handled = true;
                    }
                    break;
                default:
                    break;
            }
            return IntPtr.Zero;
        }

    }
}
